﻿using System;
using GeoAPI.Geometries;

namespace NetTopologySuite.Operation.Valid
{
	public class RepeatedPointTester
	{
		public Coordinate Coordinate
		{
			get
			{
				return this.repeatedCoord;
			}
		}

		public bool HasRepeatedPoint(IGeometry g)
		{
			if (g.IsEmpty)
			{
				return false;
			}
			if (g is IPoint)
			{
				return false;
			}
			if (g is IMultiPoint)
			{
				return false;
			}
			if (g is ILineString)
			{
				return this.HasRepeatedPoint(g.Coordinates);
			}
			if (g is IPolygon)
			{
				return this.HasRepeatedPoint((IPolygon)g);
			}
			if (g is IGeometryCollection)
			{
				return this.HasRepeatedPoint((IGeometryCollection)g);
			}
			throw new NotSupportedException(g.GetType().FullName);
		}

		public bool HasRepeatedPoint(Coordinate[] coord)
		{
			for (int i = 1; i < coord.Length; i++)
			{
				if (coord[i - 1].Equals(coord[i]))
				{
					this.repeatedCoord = coord[i];
					return true;
				}
			}
			return false;
		}

		private bool HasRepeatedPoint(IPolygon p)
		{
			if (this.HasRepeatedPoint(p.ExteriorRing.Coordinates))
			{
				return true;
			}
			for (int i = 0; i < p.NumInteriorRings; i++)
			{
				if (this.HasRepeatedPoint(p.GetInteriorRingN(i).Coordinates))
				{
					return true;
				}
			}
			return false;
		}

		private bool HasRepeatedPoint(IGeometryCollection gc)
		{
			for (int i = 0; i < gc.NumGeometries; i++)
			{
				IGeometry geometryN = gc.GetGeometryN(i);
				if (this.HasRepeatedPoint(geometryN))
				{
					return true;
				}
			}
			return false;
		}

		private Coordinate repeatedCoord;
	}
}
